package com.weiz.designpatterns.interpreter;

import java.util.Map;
import java.util.Stack;

public class Calculator {
    private final Expression expression;

    public Calculator(String expStr) {
        Stack<Expression> stack = new Stack<>();
        char[] cs = expStr.toCharArray();
        Expression left;
        Expression right;
        for (int i = 0; i < cs.length; i++) {
            switch (cs[i]) {
                // 加法
                case '+': {
                    left = stack.pop();
                    right = new VarExpression(String.valueOf(cs[i+1]));
                    stack.push(new AddExpression(left, right));
                }
                // 减法
                case '-' : {
                    left = stack.pop();
                    right = new VarExpression(String.valueOf(cs[i+1]));
                    stack.push(new SubExpression(left, right));
                }
                default :
                    stack.push(new VarExpression(String.valueOf(cs[i])));
            }
        }
        this.expression = stack.pop();
    }

    public int run(Map<String, Integer> map) {
        return this.expression.interpreter(map);
    }
}
